import * as React from 'react';
import * as _ from 'underscore';
import {UploaderStatusError} from "./uploader-status-error";


export interface UploaderStatusProps {
    queue: any[];
    errors: any[];
}

export interface UploaderStatusState {
}

export class UploaderStatus extends React.Component<UploaderStatusProps, UploaderStatusState> {
    render() {
        let className = "media-uploader-status";
        let {queue, errors} =  this.props;
        if (queue.length) {
            className += ' uploading';
        }
        if (errors.length) {
            className += ' errors';
        }

        let toggle = !!queue.length || !! errors.length;

        return (
            <div className={className} style={{display: toggle ? 'block': 'none'}}>
                <h2>上传中</h2>
                <button type="button" className="button-link upload-dismiss-errors">
                    <span className="screen-reader-text">忽略错误</span>
                </button>
                {this.renderProgressBar()}
                {this.renderInfo()}
                {this.renderErrors()}
            </div>
        );
    }

    renderProgressBar() {
        let {queue} = this.props;

        if (!queue.length) {
            return null;
        }

        let width = (_.reduce(queue, (memo, attachment) => {
                if (! attachment['uploading']) {
                    return memo + 100;
                }

                var percent = attachment['percent'];
                return memo + ( _.isNumber( percent ) ? percent : 100 );
            }, 0) / queue.length) + '%';

        return (<div className="media-progress-bar"><div style={{width: width}}></div></div>);
    }

    renderInfo() {
        let {queue} = this.props;
        if (!queue.length) {
            return null;
        }

        let index = 0;
        let active = _(queue).find((attachment, i) => {
            index = i;
            return attachment['uploading'];
        });

        return (
            <div className="upload-details">
                    <span className="upload-count">
                        <span className="upload-index">{index}</span> / <span className="upload-total">{queue.length}</span>
                    </span>
                <span className="upload-detail-separator">&ndash;</span>
                <span className="upload-filename">{active['filename']}</span>
            </div>
        );
    }

    renderErrors() {
        let {errors} = this.props;
        if (!errors.length) {
            return null;
        }
        return (
            <div className="upload-errors">
                {errors.map((error, i) => {
                    return <UploaderStatusError key={i} filename={error.filename} message={error.message}/>
                })}
            </div>
        );
    }
}
